package cn.itcast.star.graph.comfyui.client.config;

import cn.itcast.star.graph.comfyui.client.handler.ComfyuiMessageHandler;
import cn.itcast.star.graph.comfyui.client.api.ComfyuiApi;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.time.Duration;


@Configuration
public class ComfyuiConfig {

    @Bean
    public ComfyuiApi comfyuiApi() {

        //设置日志拦截器日志输出级别
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        //底层OkHttp框架实现日志功能
        OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(Duration.ofSeconds(30)) // 连接超时时间
                .readTimeout(Duration.ofSeconds(30))    //读超时时间
                .build();

        // 构建一个Retrofit客户端
        OkHttpClient okHttpClient = new OkHttpClient();
        Retrofit retrofit =new Retrofit.Builder()
//                .baseUrl("http://192.168.100.129:8188")     //指定请求的服务器地址
                .baseUrl("http://127.0.0.1:8188")     //指定请求的服务器地址
                .client(client)       //重新设定Retrofit底层使用的OkHttp客户端
                .addConverterFactory(JacksonConverterFactory.create())      //指定请求数据的转换器
                .build();
        // 返回声明Bean
        return retrofit.create(ComfyuiApi.class);
    }

    /**
     * 声明一个ws客服端并启动生效
     * @param comfyuiMessageHandler
     * @return
     */
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler) {
        WebSocketClient client = new StandardWebSocketClient();
        String url = "ws://127.0.0.1:8188/ws?clientId=star-graph";
        WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(client, comfyuiMessageHandler, url);
        webSocketConnectionManager.start();

        return webSocketConnectionManager;
    }
}
